/**
 * @ author: 汪孟苹
 */
define(["jquery", "bbcare", "jqprint", "fu/app/comm/comm", "fu/app/comm/validate", "fu/app/comm/attention",
    "scprit/followup/app/outPatient/outPatient.ui.js",
    "scprit/followup/app/outPatient/outPatient.servers.js",
    "scprit/followup/app/question/question.ui.js",
    "scprit/followup/app/question/question.event.js"
], function ($, $bb, $jqprint, $comm, $validate, $attention, $outPatientUi, $outPatientServers, $questionUi, $questionEvent) {
    var event = {}
    var clickTaskFlag = false //默认false，当点击了task-babycard名片时，变为true；
    var vm

    var URL = $bb.baseUrl("followup")
    let followQueueId = ""
    let questiones = null
    let patientInfo = null
    let curInfoStatus = ""
    let questionVal = null


    /**
     * 选择初选小结其中一个图片
     */
    var onPictureSelect = function () {
        $(this).addClass("active").siblings().removeClass("active")
        var h = $(window).height() - 221
        $(".discharge-summary .picture").css({"height": h})
        var url = $(this).children("img").attr("src")
        var $picBox = $(".discharge-summary .picture")
        var $img = $(".discharge-summary .picture img")
        $img.css({"marginTop": 0}).unbind("load")
        $img.attr("src", url).load(function () {
            if ($img.height() > 0 && $img.height() < h) {
                var top = (h - $img.height()) / 2
                $img.css({"marginTop": top})
            }
        })
        /*$("<img/>").attr("src", url).load(function() {
            var This = this;
            if( This.width >= $img.width() ){
                $img.addClass("zoom-in").css({"width":$picBox.width()}).unbind("click");
                // 放大
                $img.click(function(){
                    if( This.width > $img.width() ){
                        $img.css({"width":$img.width() + 100});
                    }else{
                        $img.css({"width":This.width});
                    }
                });
            }else{
                $img.removeClass("zoom-in");
            }
        });*/
    }

    /**
     * 翻页
     */
    var onPageClick = function () {
        var datas = $(this).data("datas")
        if (datas.type == "-1") {
            datas.arg.page--
        } else {
            datas.arg.page++
        }
        $outPatientServers.ajaxNffyyFile(datas.arg, ajaxNffyyFileCallBack, datas.className)
    }

    /**
     * 根据文件的一个地址请求文件的另一个地址成功后的回调函数
     */
    var ajaxImgFileSignUrlCallBack = function (data, arg, total, className) {
        $outPatientUi.dischargeSummary({
            "dom": $("." + className + " .modal-body"),
            "list": data.fileList,
            "pages": Math.ceil(total / arg.rows),
            "page": arg.page
        })
        $("." + className).modal("show")
        $("." + className + " .discharge-summary .list li").unbind("click")
        $("." + className + " .discharge-summary .list li").click(onPictureSelect)
        $("." + className + " .discharge-summary .list li").eq(0).click()
        $("." + className + " .discharge-summary .list .arrow-left").unbind("click")
        $("." + className + " .discharge-summary .list .arrow-left").data("datas", {
            "arg": arg,
            "className": className,
            "type": "-1"
        })
        $("." + className + " .discharge-summary .list .arrow-left").click(onPageClick)
        $("." + className + " .discharge-summary .list .arrow-right").unbind("click")
        $("." + className + " .discharge-summary .list .arrow-right").data("datas", {
            "arg": arg,
            "className": className,
            "type": "1"
        })
        $("." + className + " .discharge-summary .list .arrow-right").click(onPageClick)
    }

    /**
     * 请求绑定在该患者身上的图片成功后的回调函数
     */
    var ajaxNffyyFileCallBack = function (data, arg, className) {
        if (data.rows.length > 0) {
            var fileList = []
            for (var i = 0; i < data.rows.length; i++) {
                var obj = {}
                obj.imgUrl = data.rows[i].filePath
                obj.imgId = data.rows[i].id
                fileList.push(obj)
            }
            var params = {
                "channel": "BBCARE-APP",
                "fileList": fileList
            }
            $outPatientServers.ajaxImgFileSignUrl(params, ajaxImgFileSignUrlCallBack, arg, data.total, className)
        } else {
            $bb.toastShow("患者未上传出院小结！")
        }
    }

    /**
     * 出院小结
     */
    var onLookPicture = function () {
        var oprInfo = $(this).data("params").oprInfo
        var className = "dischargeSummaryModal"
        $bb.modal({
            "className": className,
            "size": "modal-lg",
            "tit": "出院小结（图片）",
        }, function () {
            var params = {
                "schemeBusiType": "1",
                "ptSchemeId": oprInfo.ptSchemeId,
                "userId": oprInfo.patientId,
                "page": 1,
                "rows": 6
            }
            $outPatientServers.ajaxNffyyFile(params, ajaxNffyyFileCallBack, className)
        })
    }

    /**
     * 审核
     */
    var onCheckClick = function () {
        var data = $(this).data("params")
        $bb.toastConfirmShow(function () {
            if ($validate.init()) {
                $outPatientServers.ajaxSaveQuestion(data.data, data.params, data.curInfo, getSaveCallback)
            }
        }, data, "审核通过？")
    }

    /**
     * 刷新任务列表UI
     */
    var refreshTasksUi = function (rows, curInfo) {
        $outPatientUi.showContainerInit({
            id: "showContainer",
            list: rows,
            taskId: curInfo.taskId,  // 从随访记录中跳过来，带过来的 taskId,(目的：当前标记，背景变绿)
        })
        if (curInfo.taskId === rows[0].taskId) {
            $(".show-wrapper > div.row").eq(0).addClass("active").siblings().removeClass("active")
        }
        $(function () {
            $('[data-toggle="tooltip"]').tooltip()
        })
    }
    /**
     * 请求医院的信息成功后的回调函数(打印时需要)
     */
    var handlePrintHospitalCallBack = function (hospital, info, data, printTemState) {
        // console.log('打印', data)
        $outPatientUi.printInit({
            "id": "printContent",
            "info": info,
            "data": data,
            "hospital": hospital,
            "printTemState": printTemState
        })
        $("#printContent").jqprint({
            debug: false, //如果是true则可以显示iframe查看效果（iframe默认高和宽都很小，可以再源码中调大），默认是false
            importCSS: true, //true表示引进原来的页面的css，默认是true。（如果是true，先会找$("link[media=print]")，若没有会去找$("link")中的css文件）
            printContainer: true, //表示如果原来选择的对象必须被纳入打印（注意：设置为false可能会打破你的CSS规则）。
            operaSupport: true//表示如果插件也必须支持歌opera浏览器，在这种情况下，它提供了建立一个临时的打印选项卡。默认是true
        })
        return
    }
    /**
     * 点击打印按钮
     */
    var onPrintClick = function (event) {
        var This = $(this)
        var printTemState = ""
        var h1 = '<i class="fa fa-print"></i>打印(病历本)'
        var h2 = '<i class="fa fa-print"></i>打印中'
        var h3 = '<i class="fa fa-print"></i>打印(纸质单)'  //wxf 打印
        if (This.html() == h1 || This.html() == h3) {
            if (This.html() == h1) {
                printTemState = "1"
                This.html(h2).addClass("cursor-not-allowed")
                setTimeout(function () {
                    This.html(h1).removeClass("cursor-not-allowed")
                    $("body iframe.jqprint").remove()
                }, 2000)
            } else if (This.html() == h3) {
                printTemState = "2"
                This.html(h2).addClass("cursor-not-allowed")
                setTimeout(function () {
                    This.html(h3).removeClass("cursor-not-allowed")
                    $("body iframe.jqprint").remove()
                }, 2000)
            }

            var data = This.data("params")
            var ageLabel = $("#followupAge > label").text()
            if ($("#followupAge p").length > 0) {
                var age = $("#followupAge p").text()
            } else {
                var age = $("#followupAge input").val()
            }
            $.extend(data.params, {"age": age, "ageLabel": ageLabel})
            //wxf 传纸质单和病历本  的标识
            $outPatientServers.handlePrintHospital(data.params, data.data, handlePrintHospitalCallBack, printTemState)
        }
    }

    /**
     *    点击关联其他队列
     */
    var onPatientRelation = function () {
        var data = $(this).data()
        var patientId = data.params.params.patientId
        var param = {
            patientId: patientId
        }
        $outPatientServers.getQueryQueue(param, getQueryQueueCallback)
    }

    var _checked_followQueue = undefined
    var getQueryQueueCallback = function (result, param) {
        $('.patient_relation_').show()
        $('.appendBox').empty()
        $('#_patient_next_info').data('patientId', param)
        var row_string = ''
        for (var i = 0; i < result.data.length; i++) {
            row_string += '<div class="patient_relation_content_row" data-id="' + result.data[i].id + '">' +
                '<span class="_radio_"></span>' +
                '<p>' + result.data[i].queueName + '</p>' +
                '</div>'
        }
        if (row_string === '') {
            $('.appendBox').html('<p style="text-align: center">暂时没有可添加的队列</p>')
            return
        }
        $('.appendBox').append(row_string)
        $('.patient_relation_content_row').click(function () {
            var input = $(this).find('span')[0]
            if ($(input).attr('class').indexOf('_checked_') === -1) {
                clearAllCheckedStatus()
                $(input).addClass('_checked_')
                _checked_followQueue = $(this).data('id')
            } else {
                $(input).removeClass('_checked_')
                _checked_followQueue = undefined
            }
        })
    }


    function clearAllCheckedStatus() {
        var radio = $('._radio_')
        for (var i = 0; i < radio.length; i++) {
            $(radio).removeClass('_checked_')
        }
    }

    // 点击关闭弹窗
    $('#content-main').on('click', '.close', function (e) {
        if (e.target.className === 'close' || e.target.className.indexOf('fa-times') > -1) {
            $('.patient_relation_').hide()
            _checked_followQueue = undefined
        }
    })

    $('#content-main').on('click', '#_patient_next_info', function () {
        if (!_checked_followQueue) {
            $bb.toastShow('请选择队列后提交')
            return
        }

        var param = {
            patientId: $(this).data('patientId').patientId,
            followQueueId: _checked_followQueue,
            srcTaskId: _taskGroup[0].taskId
        }
        $outPatientServers.copyPatient(param, copyPatientCallback)
    })

    var copyPatientCallback = function () {
        $bb.toastShow('添加成功')
        $('.close').cqilick()
    }


    /**
     * 2020 11 12新增建档打印
     * @printTemState { string } 当前的打印风格
     */
    var onPrintCreate = function () {
        var data = $(this).data()
        data = data.params
        var printTemState = '3'
        handlePrintHospitalCallBack({}, data.params, data.data, printTemState)
    }


    /**
     * navbar点击左右箭头进行滚动
     */
    var onNavbarRoll = function ($arrLeft, $arrRight, $wrapper, showNum, w, len, i, showWidth) {
        $arrLeft.unbind("click") //先解除绑定事件,绑定新事件
        $arrLeft.click(function () {
            if (clickTaskFlag) {
                clickTaskFlag = false
                i = 0
            }
            if (i >= showNum) {
                i--
                $wrapper.stop().animate({marginLeft: -w * (i + 1 - showNum)})
            }
        })
        $arrRight.unbind("click")
        $arrRight.click(function () {
            if (clickTaskFlag) {
                clickTaskFlag = false
                i = 0
            }
            if (i < showNum - 1) i = showNum - 1
            if (i <= len - 3) {
                i++
                $wrapper.stop().animate({marginLeft: -w * (i + 1 - showNum)})
            } else if (i == len - 2) {
                i++
                $wrapper.stop().animate({marginLeft: showWidth - w * len})
            }
        })
    }

    /**
     * navbar初始化，调用点击事件
     */
    var onNavbarRollInit = function (index) {
        var $oRow = $(".show-wrapper div.row")
        var len = $oRow.length
        var w = $oRow.eq(0).width()
        $(".show-wrapper").css("width", w * len + 'px')  // width根据.row的个数定义
        var showWidth = $("#showContainer").width() - 5		// 不知道为什么会有13px的差距 13px=>5px
        var showNum = Math.floor(showWidth / w)
        var W = w * (index + 1) - showWidth
        if (index >= showNum) {
            $(".show-wrapper").css({marginLeft: -W})
        }
        onNavbarRoll($(".arrow-left"), $(".arrow-right"), $(".show-wrapper"), showNum, w, len, index, showWidth)
    }

    /**
     * 请求患者基本信息成功后的回调函数
     */
    var getRevisedInfoParamsCallback = function (data, params, curInfo, paramsRecord) {
        params.patientName = data.PatientInfo.userName
        params.imgSrc = "page/followup/imgs/comm/" + (data.PatientInfo.gender == "F" ? "girl" : "boy") + ".png"
        params.gender = data.PatientInfo.gender
        params.taskId = curInfo.taskId
        $outPatientServers.ajaxTasks(getTasksCallback, params)

        //wxf 处理增加生长发育打通到量表里面
        var paramsRecordData = paramsRecord

        if (JSON.stringify(paramsRecordData) != "{}") {
            var userId = ""
            paramsRecordData.userId = params.patientId
            $outPatientServers.addGrowthANDRecord(params.patientId, paramsRecordData)
        }

        // allen 修改出生日期后将新日期储存
        params.birthday = data.PatientInfo.birthday
        params.expectedDay = data.PatientInfo.expectedDay
        params.pregnancyDay = data.PatientInfo.pregnancyDay
        $("#followupAge").attr("birthday", params.birthday)
        $("#followupAge").attr("expectedDay", params.expectedDay)
        $("#followupAge").attr("pregnancyDay", params.pregnancyDay)

        $bb.toastShow("保存成功！", 3000)
    }
    /**
     * 保存问卷成功后的回调方法
     */
    var getSaveCallback = function (params, curInfo, paramsRecord) {
        $outPatientServers.getRevisedInfoParams(params, curInfo, getRevisedInfoParamsCallback, paramsRecord)
    }
    /**
     * 保存随访问卷答案
     */
    var onSaveQuestion = function () {
        if ($validate.init()) {
            var data = $(this).data("params")
            $outPatientServers.ajaxSaveQuestion(data.data, data.params, data.curInfo, getSaveCallback)
        }
    }
    /**
     * 改变随访日期时，年龄随之改变
     */
    var changeAgeByFinishDate = function () {
        var time = $(this).val()
        if (time) {
            var birthday = $("#followupAge").attr("birthday")
            var expectedDay = $("#followupAge").attr("expectedDay")
            var pregnancyDay = $("#followupAge").attr("pregnancyDay")
            var paramsAge = {
                "birthday": birthday,
                "expectedDay": expectedDay,
                "pregnancyDay": pregnancyDay
            }
            var followupAge = $outPatientServers.getFollowupAge(paramsAge, time)
            $("#followupAge .control-label").html(followupAge.ageLabel)
            $("#followupAge p[name=followupAge]").html(followupAge.age)
            if ($("#followupActualAge").length > 0 && followupAge.actualAgeLabel && followupAge.actualAge) {
                $("#followupActualAge .control-label").html(followupAge.actualAgeLabel)
                $("#followupActualAge p[name=followupActualAge]").html(followupAge.actualAge)
            }
        } else {
            $("#followupAge p[name=followupAge]").html("")
            $("#followupActualAge p[name=followupActualAge]").html("")
        }
    }
    /**
     * 锚点事件
     */
    var anchorMenuEvent = function () {
        $("#anchorMenu .anchor-menu-fold").click(function () {
            $("#anchorMenu .anchor-menu-unfold").show()
            $("#anchorMenu .anchor-menu-fold").hide()
        })
        $("#anchorMenu .anchor-menu-unfold .anchor-menu-close").click(function () {
            $("#anchorMenu .anchor-menu-fold").show()
            $("#anchorMenu .anchor-menu-unfold").hide()
        })
        $("#anchorMenu .anchor-menu-unfold ul li").click(function () {
            $(this).addClass("active").siblings().removeClass("active")
        })
        var obj = document.getElementById("content-main")
        if (obj.scrollHeight > obj.clientHeight || obj.offsetHeight > obj.clientHeight) {
            $("#anchorMenu").css({"right": "27px"})
            $("#lisAndPacs").css({"right": "27px"})

        } else {
            $("#anchorMenu").css({"right": "20px"})
            $("#lisAndPacs").css({"right": "20px"})
        }
    }
    /**
     * 请求问卷成功后的回调方法
     */
    var getQuestionCallback = function (data, params, curInfo, addTaskInfo) {
        followQueueId = params.followQueueId
        questiones = data.questiones
        patientInfo = data.patientInfo
        curInfoStatus = curInfo.status
        questionVal = data.values
        // console.log('data.values77777', data.values)
        $outPatientUi.followUpInit({
            id: "followUpInfo",
            list: data.questiones,	  // 问卷
            status: curInfo.status,
            task: data.task,	 // 随访指导
            ageRelate: params,	// 随访指导里的随访年龄相关数据
            sampleList: data.sampleList
        })
        /* 改变随访日期时，年龄随之改变 begin */
        $("input[name=finishDate]").unbind("change")
        $("input[name=finishDate]").change(changeAgeByFinishDate)
        /* end 改变随访日期时，年龄随之改变 */
        $questionUi.init({
            id: "questions",
            status: curInfo.status,
            list: data.questiones,	  // 问卷
            values: $comm.handleValue(data.patientInfo, data.values),
            initParams: {
                "queueId": params.followQueueId
            }
        })
        $questionEvent.init({
            "getGrowth": {
                "patientId": data.oprInfo.patientId,
                "preTaskId": curInfo.preTaskId,
                "followQueueId": params.followQueueId,
                "gender": params.gender
            },
            "getTextareaAssess": {
                "userId": params.patientId,
                "taskId": curInfo.taskId
            }
        })
        $outPatientUi.anchorMenuInit({
            "id": "anchorMenu",
            "list": data.questiones
        })

        // 如果是入托入学体验则需临时将数据渲染到打印页备用并渲染打印按钮
        renderRuXueData(data)
        reverseSelection('input[type=radio][name="sf_yjz_March_qw"]')
        reverseSelection('input[type=radio][name="sf_yjz_June_qw"]')
        reverseSelection('input[type=radio][name="sf_yjz_August_qw"]')
        reverseSelection('input[type=radio][name="sf_yjz_Dec"]')
        reverseSelection('input[type=radio][name="sf_yjz_sby_qw"]')
        reverseSelection('input[type=radio][name="sf_yjz_essy_qw"]')
        reverseSelection('input[type=radio][name="sf_yjz_Lsb_qw"]')
        reverseSelection('input[type=radio][name="sf_yjz_ssui_qw"]')

        // 给临时随访修改按钮添加点击事件
        $('.content-main').on('click', '.__edit', function (e) {
            e.stopPropagation()
            vm.addTaskConfirm.form.id = $(this).attr('id')
            vm.addTaskConfirm.show = true
            vm.addTaskConfirm.title = '修改临时节点'
            vm.addTaskConfirm.buttonText.confirm = '修改临时节点'
            vm.addTaskConfirm.params = $('.content-main').data()
            vm.addTaskConfirm.form.date = $(this).attr('date')
            vm.addTaskConfirm.form.age = vm.getCurrentAge($(this).attr('date'))
        })


        /**
         * 2021 4 7
         * 初始化 VUE 弹出框
         */
        $('#root').show()


        // 锚点事件
        anchorMenuEvent()
        $attention.init()
        $('.validatebox').data("attentionFun", $attention.blurInit)	// 校验之前提示警告
        $validate.blurInit()
        $.extend(curInfo, {"addTaskFlag": addTaskInfo.addTaskFlag})
        var params02 = {
            callback1: onPatientDelect,
            callback2: onSaveQuestion,
            callback3: onChangeCanWrite,
            callback4: onAddTask,
            callback5: onPrintClick,
            callback6: onCheckClick,
            callback7: onResetData,
            callback8: onDeleteTemporary,
            callback9: onLookPicture,
            callback10: onPrintClick,  		// wxf 打印
            callback11: onPatientRelation,  // 关联其他队列
            callback12: onPrintCreate,		// 建档打印
            callback13: onReserve,    		// 标记预约
            callback14: onReserveDetail,	// 预约详情
            callback16: onFinishFollow,		// 终止随访
            callback15: onSharePhoto, // 分享照片
            callback17: onPrintTheReportSheet, // 打印报告单
            params1: $outPatientServers.getDeleteParams(),
            params2: {data: data, params: params, curInfo: curInfo},
            params3: {data: data, params: params, curInfo: curInfo, addTaskInfo: addTaskInfo},
            params4: {
                params: params,
                afterTaskId: addTaskInfo.afterTaskId,
                fun: $outPatientServers.ajaxTasks,
                getTasksCallback: getTasksCallback
            },
            params5: {data: data, params: params, curInfo: curInfo},
            params6: {data: data, params: params, curInfo: curInfo},
            params7: {data: data, params: params, curInfo: curInfo, addTaskInfo: addTaskInfo},
            params8: {
                params: params,
                afterTaskId: addTaskInfo.afterTaskId,
                fun: $outPatientServers.ajaxTasks,
                deleteTasksCallback: deleteTasksCallback,
                taskId: curInfo.taskId
            },
            params9: {oprInfo: data.oprInfo},
            params10: {data: data, params: params, curInfo: curInfo}, 	// wxf 打印
            params11: {data: data, params: params, curInfo: curInfo},	// 关联队列
            params12: {data: data, params: params},				// 建档打印
            params13: {data: data, params: params, vm: vm},		// 标记预约
            params14: {data: data, params: params, vm: vm},		// 预约详情
            params16: {data: data, params: params, vm: vm},		// 终止随访
            params15: {data: data, params: params, vm: vm}, // 照片分享
            params17: {data: data, params: params, curInfo: curInfo}, // 打印报告单
        }
        var topbars = $outPatientServers.handleBtnGroup(curInfo, params02)
        $bb.toolbar(topbars)
    }


    // 预警征反选
    function reverseSelection(el) {
        $(el).parent().parent().parent().nextAll().each(function (i, value) {
            $(value).on('click', 'input[type=radio]', function () {
                let flag = []
                $(el).parent().parent().parent().nextAll().each(function (i, val) {
                    if ($(val).children().children().children().attr('checked') == 'checked') {
                        flag.push(true)
                    } else {
                        flag.push(false)
                    }
                })
                if (flag.indexOf(false) > -1) {
                    $(el).removeAttr('checked')
                } else {
                    $(el).attr('checked', 'true')
                }
            })

        })
    }

    var onAddTask = function () {
        var data = $(this).data("params")
        // $bb.toastConfirmShow($outPatientServers.ajaxAddTask,data,"确定添加临时随访?");
        vm.addTaskConfirm.form.id = ''
        vm.addTaskConfirm.show = true
        vm.addTaskConfirm.params = data
        vm.addTaskConfirm.title = '创建临时节点'
        var targetDate = getCurrentDate(new Date())
        vm.addTaskConfirm.form.age = vm.getCurrentAge(targetDate)
        vm.addTaskConfirm.form.date = targetDate
    }

    var getFormatDate = function (date) {
        var year = date.getFullYear()
        var month = date.getMonth() + 1
        var day = date.getDate()
        var time = [year, month, day]
        time = time.map(function (t) {
            return t < 10 ? '0' + t : t
        })
        return time.join('-')
    }

    function getCurrentDate() {
        var date = new Date(),
            year = date.getFullYear(),
            month = date.getMonth() + 1,
            day = date.getDate()

        function addZore(num) {
            return num < 10 ? '0' + num : num
        }

        return `${year}-${addZore(month)}-${addZore(day)}`
    }

    var onFinishFollow = function () {
        var data = $(this).data('params')
        $outPatientServers.queryClosedRecord(data.params.patientId, function (res) {
            if (res.success) {
                vm.finishDialog.name = data.params.patientName
                vm.finishDialog.show = true
                vm.finishDialog.data = data
            } else {
                vm.$message.error(res.msg)
            }
        })
    }
    /**
     * 2021 4 28
     * 照片分享
     */
    var onSharePhoto = function () {
        var data = $(this).data('params')
        var vm = data.vm
        vm.photoShare.show = true
    }

    var onPrintTheReportSheet = function () {
        var datas = $(this).data()
        var data = datas.params.data

        var dataForm = {...data.patient, ...data.values}
        dataForm.ncz_xdtjc.length > 2 ? dataForm.ncz_xdtjc = '已检查' : dataForm.ncz_xdtjc = '未检查'
        dataForm.ncz_jdmcc.length > 2 ? dataForm.ncz_jdmcc = '已检查' : dataForm.ncz_jdmcc = '未检查'
        if (dataForm.ncz_zywxys == undefined) {
            dataForm.ncz_zywxys = ''
        }
        if (dataForm.scaleAssessStatus == undefined) {
            dataForm.scaleAssessStatus = ''
            dataForm.ncz_nczfxpjs = ''
        } else {
            dataForm.scaleAssessStatus.indexOf("高危") > -1 ? dataForm.ncz_nczfxpjs = "未来10年发生缺血性心血管疾病的绝对危险为2.1%，未来10年发生缺血性心血管疾病的危险是同性别，同年龄人群平均水平的1.500倍，是同性别、同年龄人群理想水平的5.250倍" : dataForm.ncz_nczfxpjs = ""
        }
        dataForm.age = showAge(dataForm.birthday)

        // console.log(dataForm)

        // var el = document.getElementById("printcontent");
        var iframe = document.createElement('IFRAME');
        var doc = "";
        iframe.setAttribute("id", "print-iframe");
        // iframe.setAttribute('style', 'zoom:0.9');
        document.body.appendChild(iframe);
        doc = iframe.contentWindow.document;
        //这里可以自定义样式
        doc.write('<div>' +
            ' <div id="egg"> ' +
            '       <div style="text-align: center;padding: 1px 0 5px 0;width: 100%;">' +
            '           <h3 style="font-weight: 700;font-size: 20px;width: 100%;">脑卒中高危人群筛查和干预项目参与对象脑卒中风险评估报告</h3>' +
            '       </div>' +
            '       <div style="">' +
            '           <table style="text-align: center;border-spacing:0;border-left:1px solid black;border-top:1px solid black ;zoom: 0.8">' +
            '               <tbody>' +
            '                   <tr style="height: 30px;">' +
            '                       <td width="25%" style="text-align: left;padding-left: 5px;border-bottom: 1px solid black;border-right: 1px solid black">姓名： ' +
            dataForm.userName +
            '                       </td>' +
            '                       <td width="20%" style="text-align: left;padding-left: 5px;border-bottom: 1px solid black;border-right: 1px solid black">年龄：' +
            dataForm.age +
            '                       岁</td>' +
            '                       <td colspan="3" width="50%" style="text-align: left;padding-left: 5px;border-bottom: 1px solid black;border-right: 1px solid black">身份证号：' +
            dataForm.idCard +
            '</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                       <td colspan="5" style="border-bottom: 1px solid black;border-right: 1px solid black;text-align: left;padding-left: 5px" width="100%">筛查干预单位：济源市人民医院（神经外科）</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                       <td colspan="5" style="border-bottom: 1px solid black;border-right: 1px solid black;text-align: left;padding-left: 5px">1.本次调查结果</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                       <td colspan="5" style="border-bottom: 1px solid black;border-right: 1px solid black;text-align: left;padding-left: 5px">检查检验结果：（备注：以下参考值范围均参考第八版《诊断学》）' +
            '                       </td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">项目</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">结果</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">单位</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">参考值</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">心电图检查</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">身高</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            dataForm.Height +
            '                       </td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">cm</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">--</td>' +
            '                       <td rowSpan="4" style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            dataForm.ncz_xdtjc +
            '                       </td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">体重</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            dataForm.Weight +
            '                       </td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">kg</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">--</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">BMI</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            dataForm.BodyMassIndex +
            '                       </td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">kg/m2</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">18.5~23.9</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">收缩压</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            dataForm.ncz_ssy +
            '                       </td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">mmHg</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">90~140</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">舒张压</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            dataForm.ncz_sxy +
            '                       </td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">mmHg</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">60~90</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">颈部血管超声检查</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">空腹血糖</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            dataForm.ncz_kfxt +
            '                       </td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">mmol/L</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">3.9~6.1</td>' +
            '                       <td rowSpan="8" style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            dataForm.ncz_jdmcc +
            '                       </td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">餐后2小时血糖</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            dataForm.ncz_ch2xsxt +
            '                       </td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">mmol/L</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">3.9~7.8</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">糖化血红蛋白</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            dataForm.ncz_thxhdb +
            '                       </td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">%</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">4%~6%</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">甘油三酯</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            dataForm.ncz_gysz +
            '                       </td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">mmol/L</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">0.56~1.70</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">总胆固醇</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            dataForm.ncz_zdgc +
            '                       </td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">mmol/L</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;"> <5.2 </td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">低密度脂蛋白胆固醇</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            dataForm.ncz_dmdzdbdgc +
            '                       </td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;">mmol/L</td>' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;"> ≤3.12</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                      <td style="border-bottom: 1px solid black;border-right: 1px solid black;">高密度脂蛋白胆固醇</td>' +
            '                      <td style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            dataForm.ncz_gmdzdbdgc +
            '                       </td>' +
            '                      <td style="border-bottom: 1px solid black;border-right: 1px solid black;">mmol/L</td>' +
            '                      <td style="border-bottom: 1px solid black;border-right: 1px solid black;">1.03~2.07</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;">' +
            '                      <td style="border-bottom: 1px solid black;border-right: 1px solid black;">同型半胱氨酸</td>' +
            '                      <td style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            dataForm.ncz_txbgas +
            '                      </td>' +
            '                      <td style="border-bottom: 1px solid black;border-right: 1px solid black;">umol/L</td>' +
            '                      <td style="border-bottom: 1px solid black;border-right: 1px solid black;">5~15</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;text-align: left">' +
            '                       <td colspan="5" style="border-bottom: 1px solid black;border-right: 1px solid black;padding-left: 5px">主要危险因素：</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;text-align: left">' +
            '                       <td colspan="5" style="border-bottom: 1px solid black;border-right: 1px solid black;height: 50px;padding-left: 20px">' +
            dataForm.ncz_zywxys +
            '                       </td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;text-align: left">' +
            '                        <td colspan="5" style="border-bottom: 1px solid black;border-right: 1px solid black;padding-left: 5px">2.脑卒中风险评级</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;text-align: left">' +
            '                       <td colspan="5" style="border-bottom: 1px solid black;border-right: 1px solid black;height: 40px;padding-left: 10px">' +
            dataForm.ncz_nczfxpj +
            '                       </td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;text-align: left">' +
            '                       <td colspan="5" style="border-bottom: 1px solid black;border-right: 1px solid black;height: 65px;padding-left: 10px"> ' +
            dataForm.ncz_nczfxpjs +
            '                      </td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;text-align: left">' +
            '                      <td colspan="5" style="border-bottom: 1px solid black;border-right: 1px solid black;padding-left: 5px">3.针对您的主要危险因素我们给予如下建议</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;text-align: left">' +
            '                       <td colspan="5" style="border-bottom: 1px solid black;border-right: 1px solid black;padding-left: 5px">（1）健康指导</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;text-align: left">' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;padding-left: 5px">合理膳食</td>' +
            '                       <td colspan="4" style="border-bottom: 1px solid black;border-right: 1px solid black;padding-left: 5px">低盐；低脂；控制肉类食物；增加水果和蔬菜摄入量；</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;text-align: left">' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;padding-left: 5px">改善生活习惯</td>' +
            '                       <td colspan="4" style="border-bottom: 1px solid black;border-right: 1px solid black;padding-left: 5px">控制体重；心理平衡；戒酒</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;text-align: left">' +
            '                       <td style="border-bottom: 1px solid black;border-right: 1px solid black;padding-left: 5px">定期检查</td>' +
            '                       <td colspan="4" style="border-bottom: 1px solid black;border-right: 1px solid black;padding-left: 5px">血压；血糖；血脂</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;text-align: left">' +
            '                      <td colspan="5" style="border-bottom: 1px solid black;border-right: 1px solid black;padding-left: 5px">如果您出现了以下症状--请立即拨打120!</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;text-align: left">' +
            '                       <td colspan="5" style="border-bottom: 1px solid black;border-right: 1px solid black;">' +
            '                           <ul>' +
            '                               <li style="list-style: disc">突然的颜面部、肢体的麻木或无力，尤其是在身体的一侧</li>' +
            '                               <li style="list-style: disc">突然说不出物体的名称，说话或理解困难</li>' +
            '                               <li style="list-style: disc">突然出现嗜睡状态，即患者昏昏沉沉，总想睡觉</li>' +
            '                               <li style="list-style: disc">突然行走困难，头晕，伴有恶心、呕吐，肢体失去平衡或不协调</li>' +
            '                               <li style="list-style: disc">突然单眼或双眼视物不清</li>' +
            '                               <li style="list-style: disc">突然的不明原因的没有经历过的严重头痛，可有恶心呕吐</li>' +
            '                           </ul>' +
            '                       </td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;text-align: left">' +
            '                       <td colspan="5" style="border-bottom: 1px solid black;border-right: 1px solid black;padding-left: 5px">(2)用药、手术及其他建议(250字符以内)</td>' +
            '                   </tr>' +
            '                   <tr style="height: 30px;text-align: left">' +
            '                       <td colspan="5" style="border-bottom: 1px solid black;border-right: 1px solid black;padding-left: 5px">低盐低脂糖尿病饮食;监测血压，建议继续规律口服降压药物;限酒;适当运动，减轻体重;监测血糖，建议糖尿病专科明确糖尿病诊断;定期市人民医院门诊2楼255室脑卒中筛查与干预门诊随诊，不适随诊。 </td>' +
            '                   </tr>' +
            '               </tbody>' +
            '           </table>' +
            '       </div>' +
            '   </div>' +
            '</div>');
        doc.close();
        iframe.contentWindow.focus();
        iframe.contentWindow.print();
        if (navigator.userAgent.indexOf("MSIE") > 0) {
            document.body.removeChild(iframe);
        }

    }
    var showAge = function (value) {

        // 指定日期

        let birthdays = new Date(value.replace(/-/g, "/"))

        // 当前系统日期

        let d = new Date();

        let age = d.getFullYear() - birthdays.getFullYear() - (d.getMonth() <
        birthdays.getMonth() || (d.getMonth() == birthdays.getMonth() &&
            d.getDate() < birthdays.getDate()) ? 1 : 0);

        return age

    }


    /**
     * 判断是否为入托入学体验
     * @data { object } 返回的数据集合
     */
    var renderRuXueData = function (data) {
        var system_title = document.getElementById('followUpTit')
        system_title = system_title.getElementsByClassName('tit')[0].innerText
        if (system_title.indexOf('入托入学') === -1) return
        $('#ry-mz').text(data.values.Pub1100002)
        $('#ry-xb').text(data.values.Pub1100003)
        $('#ry-nj').text(getAge(data.values.Pub1100004))
        $('#ry-csrq').text(data.values.Pub1100005)
        var headStr = ''
        for (var i in data.values) {
            if (i.indexOf('_') > -1 && headStr == '') {
                headStr = i.split('_')[0]
            }
        }
        var jwhbs = getValue(headStr, data.values, 'jwhbqk')
        jwhbs = jwhbs ? jwhbs : ''
        if (jwhbs.indexOf('其他') > -1) {
            jwhbs = jwhbs.replace(/其他/g, getValue(headStr, data.values, 'jqtwhbqk'))
        }
        if (jwhbs.indexOf('[') > -1) {
            jwhbs = JSON.parse(jwhbs).join(',')
        }
        $('#ry-jwbs').text(jwhbs)
        $('#ry-gms').text(getValue(headStr, data.values, 'gms'))
        $('#ry-tz').text(getValue(headStr, data.values, 'tizhong'))
        $('#ry-tzpj').text(getValue(headStr, data.values, 'tzpj'))
        $('#ry-sg').text(getValue(headStr, data.values, 'shgao') + 'cm')
        $('#ry-sgpj').text(getValue(headStr, data.values, 'sgpj'))
        $('#ry-zy').text(getValue(headStr, data.values, 'zy') === '' ? '左：-' : '左：' + getValue(headStr, data.values, 'zy'))
        $('#ry-yy').text(getValue(headStr, data.values, 'yy') === '' ? '右：-' : '右：' + getValue(headStr, data.values, 'yy'))
        $('#ry-zsl').text(getValue(headStr, data.values, 'zysl') === '' ? '未测' : '左：' + getValue(headStr, data.values, 'zysl'))
        $('#ry-ysl').text(getValue(headStr, data.values, 'yysl') === '' ? '未测' : '右：' + getValue(headStr, data.values, 'yysl'))
        $('#ry-ze').text(getValue(headStr, data.values, 'zuoer') === '' ? '左：-' : '左：' + getValue(headStr, data.values, 'zuoer'))
        $('#ry-ye').text(getValue(headStr, data.values, 'youer') === '' ? '右：-' : '右：' + getValue(headStr, data.values, 'youer'))
        $('#ry-ycs').text(getValue(headStr, data.values, 'ycs'))
        $('#ry-qcs').text(getValue(headStr, data.values, 'qcs'))
        $('#ry-tl').text(getValue(headStr, data.values, 'toulu') === '' ? '-' : getValue(headStr, data.values, 'toulu'))
        $('#ry-xk').text(getValue(headStr, data.values, 'xiongl') === '' ? '-' : getValue(headStr, data.values, 'xiongl'))
        $('#ry-jzsz').text(getValue(headStr, data.values, 'jzsz') === '' ? '-' : getValue(headStr, data.values, 'jzsz'))
        $('#ry-yb').text(getValue(headStr, data.values, 'yanbu') === '' ? '-' : getValue(headStr, data.values, 'yanbu'))
        $('#ry-xf').text(getValue(headStr, data.values, 'xinf') === '' ? '-' : getValue(headStr, data.values, 'xinf'))
        $('#ry-gp').text(getValue(headStr, data.values, 'ganpi') === '' ? '-' : getValue(headStr, data.values, 'ganpi'))
        $('#ry-wszq').text(getValue(headStr, data.values, 'wszq') === '' ? '-' : getValue(headStr, data.values, 'wszq'))
        $('#ry-pf').text(getValue(headStr, data.values, 'pifu') === '' ? '-' : getValue(headStr, data.values, 'pifu'))
        $('#ry-xhdb').text(getValue(headStr, data.values, 'xhdb'))
        $('#ry-basajzym').text(getValue(headStr, data.values, 'alt'))
        $('#ry-ygbmky').text(getValue(headStr, data.values, 'ygbmky'))
        $('#ry-ygbmkt').text(getValue(headStr, data.values, 'ygbmkt'))
        $('#ry-ygeky').text(getValue(headStr, data.values, 'ygeky'))
        $('#ry-ygekt').text(getValue(headStr, data.values, 'ygekt'))
        $('#ry-yghxkt').text(getValue(headStr, data.values, 'ygxkt'))
        $('#ry-bgkt').text(getValue(headStr, data.values, 'bgkt'))
        $('#ry-mdkt').text(getValue(headStr, data.values, 'mdkt'))
        $('#ry-hivkt').text(getValue(headStr, data.values, 'hivkt'))
        $('#ry-other').text(getValue(headStr, data.values, 'fzjcqt'))
        $('#ry-jcjg').text(getValue(headStr, data.values, 'jcjg'))
        $('#ry-ysyj').text(getValue(headStr, data.values, 'ysyj'))
        $('#ry-ysqm').text(getValue(headStr, data.values, 'ysqm'))
        var date
        try {
            date = getValue(headStr, data.values, 'tjrq')
            date = date.split('-')
            date = date[0] + '年' + date[1] + '月' + date[2] + '日'
        } catch (err) {
            date = getValue(headStr, data.values, 'tjrq')
        }
        $('#ry-tjrq').text(date)

        renderRuXueBtn()
    }

    /**
     * 获取元素的值，在不同的配置下字段是同字段，所以要单独处理
     * @param { string } name 相同的头部字段
     * @param { object } data 值
     * @param { string } str  不同的尾部字段
     */
    function getValue(name, data, str) {
        return data[name + '_' + str]
    }

    var renderRuXueBtn = function () {
        var system_title = ''
        try {
            system_title = document.getElementById('followUpTit')
            system_title = system_title.getElementsByClassName('tit')[0].innerText
        } catch (err) {
            console.log('获取系统名失败')
        }
        if (system_title.indexOf('入托入学') === -1) return
        // 创建打印按钮
        var print_dom = document.createElement('li')
        print_dom.innerHTML = '<i class="fa fa-print"></i>入园入托打印'
        print_dom.onclick = function () {
            document.getElementsByClassName('ruyuan-print')[0].style.display = "block"
            window.print()
        }
        // 添加打印按钮
        var navbar_meun_dom = document.getElementById('topbar')
        var timer = undefined
        timer = setInterval(function () {
            if (navbar_meun_dom.children[0]) {
                var wrapper = navbar_meun_dom.children[0]
                wrapper.appendChild(print_dom)
                clearInterval(timer)
            }
        }, 4)
        // 监听打印时间
        var mediaQueryList = window.matchMedia('print')
        mediaQueryList.addListener(function (mql) {
            if (!mql.matches) {
                document.getElementsByClassName('ruyuan-print')[0].style.display = "none"
            }
        })
        window.onafterprint = function () {
            document.getElementsByClassName('ruyuan-print')[0].style.display = "none"
        }
    }


    var getAge = function (strAge) {
        var that_time = new Date(strAge).getTime()
        var current_time = new Date().getTime()
        if (current_time - that_time < 0) return
        var reduce = (current_time - that_time) / 1000
        var year = Math.floor(reduce / 365 / 24 / 60 / 60)
        var month = Math.floor((reduce - year * 365 * 24 * 60 * 60) / 30 / 24 / 60 / 60)
        return year + '岁' + month + '月龄'
    }
    /**
     * 点击修改按钮将问卷转化为可写状态
     */
    var onChangeCanWrite = function () {
        var data = $(this).data("params")
        data.curInfo.status = "default"
        getQuestionCallback(data.data, data.params, data.curInfo, data.addTaskInfo)
    }

    /**
     * 2021 4 7
     * 点击标记预约
     */
    var onReserve = function () {
        var data = $(this).data("params")
        var vm = data.vm
        vm.dialog.show = false
        vm.dialog.title = '到院日期：'
        vm.dialog.show = true
    }
    /**
     * 点击详情
     */
    var onReserveDetail = function () {
        var data = $(this).data("params")
        var vm = data.vm
        vm.detail.show = false
        vm.detail.show = true
        setTimeout(function () {
            vm.detail.loading = false
        }, 1000)
    }


    /**
     * 切换随访任务
     */
    var onTaskSelect = function () {
        var data = $(this).data()
        var curInfo = data.curInfo
        var index
        if (data.flag) {
            index = 0
            clickTaskFlag = true
            $(".show-wrapper").css({"marginLeft": 0})
        } else if (typeof data.params._index == 'number') {
            index = data.params._index
            var left = data.params._left
            $(".show-wrapper").css({"marginLeft": left})
            delete data.params._index
            delete data.params._left
            $('.content-main').data(data)
        } else {
            index = $(this).index()
        }
        $(".show-wrapper > div.row").eq(index).addClass("active").siblings().removeClass("active")
        var curData = data.rows[index]
        curInfo.taskId = curData.taskId
        curInfo.taskStatus = curData.taskStatus
        curInfo.status = $outPatientServers.curTaskStatus(curData.taskStatus)
        curInfo.seqNo = curData.seqNo
        curInfo.preTaskId = curData.preTaskId
        curInfo.auditStatus = curData.auditStatus
        curInfo.isTemporary = $(this).text().indexOf("临时随访") != -1 ? 1 : 0
        // 若点击的任务是审核状态，则表单的titlt也要给出待审核提示。
        if (curData.auditStatus == "4") {
            $("#followUpTit .tit").html('<i class="fa fa-question-circle" aria-hidden="true" data-toggle="tooltip" data-placement="left" title="内容待审核"></i>' + data.params.queuename)
        } else {
            $("#followUpTit .tit").html(data.params.queuename)
        }
        $(function () {
            $('[data-toggle="tooltip"]').tooltip()
        })


        $outPatientServers.ajaxQuestion(data.params, curInfo, getQuestionCallback, data.addTaskInfo)

    }

    let ajaxQueryFamilyInfoCallback = function (data) {
        if (data) {
            let newVal = {...questionVal, ...data.values}
            $questionUi.init({
                id: "questions",
                status: curInfoStatus,
                list: questiones,	  // 问卷
                values: $comm.handleValue(patientInfo, newVal),
                initParams: {
                    "queueId": followQueueId
                }
            })
        }
    }
    /**
     * 母亲手机号查询既往数据
     */
    // $('.content-main').on('blur', 'input[name=Pub1100001]', function () {
    // 	console.log($(this).val())
    // 	console.log('followQueueId', followQueueId)
    // 	let phone = $(this).val()
    // 	let data = $(this).data()
    // 	$outPatientServers.ajaxQueryFamilyInfo(followQueueId, phone, ajaxQueryFamilyInfoCallback)
    // })

    event.initVue = function () {
        if (vm) vm = undefined
        vm = new Vue({
            el: "#root",
            data: function () {
                return {
                    dialog: {
                        show: false,
                        date: '',
                        loading: false,
                        title: '',
                        pickerOptions: {
                            disabledDate: function (time) {
                                return time.getTime() + 24 * 3600 * 1000 < Date.now()
                            }
                        },
                        noon: 1    // 1 上午 2 下午
                    },
                    detail: {
                        show: false,
                        data: [],
                        total: 0,
                        current: 1,
                        pageSize: 5,
                        loading: true
                    },
                    photoShare: {
                        show: false,
                        loading: false,
                        list: [],
                        preview: {
                            show: false,
                            imgSrc: ''
                        },
                        listLength: 0,
                        readyList: [],
                        userId: '',
                        tenantId: '',
                        history: {
                            list: [],
                            loading: false,
                            current: 1,
                            size: 10,
                            text: '加载更多',
                            show: false
                        }
                    },
                    height: 0,
                    finishDialog: {
                        option: 1,
                        other: '',
                        show: false,
                        name: '该用户',
                        data: null
                    },
                    creator: '',
                    addTaskConfirm: {
                        show: false,
                        params: null,
                        title: '',
                        buttonText: {
                            cancel: '取消',
                            confirm: '创建节点'
                        },
                        form: {
                            date: getFormatDate(new Date()),
                            name: '临时随访',
                            age: '',
                            id: '',
                        },
                        rules: {
                            date: [
                                {required: true, message: '请选择临时随访日期', trigger: 'blur'},
                            ],
                            // name: [
                            // 	{ required: true, message: '请输入临时随访名称', trigger: 'blur' },
                            // 	{ min: 1, max: 8, message: '长度在 1 到 8 个字符', trigger: 'blur' }
                            // ]
                        }
                    }
                }
            },
            created: function () {
                this.getList()
                var that = this
                try {
                    var account = JSON.parse(sessionStorage.getItem('account'))
                    var currentProjectName = $('.tenant_name').text()
                    account.apps.forEach(function (item) {
                        if (item.tenantName == currentProjectName) that.photoShare.tenantId = item.tenantId
                    })
                    this.creator = account.alias
                } catch (err) {
                }
                var params = $('.content-main').data().params
                this.photoShare.userId = params.patientId
                // this.getPhotoList()
            },
            mounted: function () {
                var height = document.documentElement.clientHeight - 82
                this.height = height
            },
            methods: {
                handleChangePage: function (current) {
                    this.detail.current = current
                    this.getList()
                },
                getStatus: function (status) {
                    switch (status) {
                        case 1 || '1':
                            return '进行中'
                        case 2 || '2':
                            return '已完成'
                        case 3 || '3':
                            return '已过期'
                        case 4 || '4':
                            return '待确认'
                    }
                },
                handleChangeTaskConfirm: function (val) {
                    var date = getFormatDate(val)
                    this.addTaskConfirm.form.age = this.getCurrentAge(date)
                    this.addTaskConfirm.form.date = date
                },
                handleShowTaskConfirm: function () {
                    this.addTaskConfirm.params.executeTime = this.addTaskConfirm.form.date
                    this.addTaskConfirm.params.actualAge = this.addTaskConfirm.form.age
                    if (!this.addTaskConfirm.form.id) {
                        $outPatientServers.ajaxAddTask(this.addTaskConfirm.params)
                    } else {
                        var params = {
                            taskId: this.addTaskConfirm.form.id,
                            executeTime: this.addTaskConfirm.params.executeTime,
                            actualAge: this.addTaskConfirm.params.actualAge
                        }
                        $outPatientServers.ajaxUpDateTask(params, function () {
                            var mainParam = $('.content-main').data().params
                            var index = $('#showContainer .active').index()
                            var left = $('.show-wrapper').css('margin-left')
                            mainParam._index = index
                            mainParam._left = left
                            $('.content-main').data(mainParam)
                            $outPatientServers.ajaxTasks(getTasksCallback, mainParam)
                        })
                    }
                    vm.addTaskConfirm.show = false
                },
                handleSubmit: function () {
                    if (!this.dialog.date) return this.$message.error('请选择日期后提交')
                    this.dialog.loading = true
                    var that = this
                    var ajax_params = {
                        userId: data.oprInfo.patientId,
                        queueId: data.oprInfo.followQueueId,
                        taskId: curInfo.taskId,
                        appointType: 1,
                        appointTime: this.stringifyTime(this.dialog.date),
                        appointTimeType: Number(this.dialog.noon),
                        remark: ''
                    }
                    $outPatientServers.markAppointment(ajax_params, function (res) {
                        if (res.success) {
                            that.$message.success('预约成功')
                            that.dialog.show = false
                        } else {
                            that.$message.error('预约失败')
                        }
                        that.dialog.loading = false
                    })
                },
                stringifyTime: function (date) {
                    var year = date.getFullYear(),
                        month = date.getMonth() + 1,
                        day = date.getDate()
                    //    hours = date.getHours(),
                    //      min = date.getMinutes(),
                    // 	 sec = date.getSeconds()
                    // return year + '-' + month + '-' + day + ' ' + this.addZore(hours) + ':' + this.addZore(min) + ':' + this.addZore(sec)
                    return year + '-' + month + '-' + day
                },
                addZore: function (num) {
                    return num < 10 ? '0' + num : num
                },
                handleFinishFollowupCallback: function () {
                    var f = this.finishDialog, that = this
                    if (!f.option) return this.$message.error('请选择终止随访的原因!')
                    if (f.option == 3 && f.other == '') return this.$message.error('请填写其他终止原因!')
                    $bb.ajax({
                        url: URL + 'followup/service/patient/closecase',
                        data: JSON.stringify({
                            data: {
                                followQueueId: f.data.data.oprInfo.followQueueId,
                                patientId: f.data.data.oprInfo.patientId,
                                ptSchemeId: f.data.data.oprInfo.ptSchemeId,
                                closeReason: f.option == 1 ? '死亡' : f.option == 2 ? '失访' : f.other,
                                taskId: f.data.data.task.ptTaskId,
                            }
                        }),
                        success: function (res) {
                            if (res.success) {
                                that.$message.success('结案成功')
                                that.finishDialog.show = false
                            } else {
                                that.$message.error(res.msg)
                            }
                        }
                    })
                },
                getList: function () {
                    var that = this
                    this.detail.loading = true
                    var data = $('.content-main').data()
                    var ajax_params = {
                        currentPage: this.detail.current,
                        pageSize: this.detail.pageSize,
                        userId: data.patientId,
                        queueId: data.followQueueId,
                        taskId: data.taskId
                    }
                    $outPatientServers.getAppointmentDetail(ajax_params, function (res) {
                        if (res.success) {
                            that.detail.data = res.data.data
                            that.detail.total = res.data.count
                        } else {
                            that.$message.error('获取详情列表错误')
                        }
                        that.detail.loading = false
                    })
                },
                getCurrentAge: function (target) {
                    var params = this.addTaskConfirm.params.params
                    var paramsAge = {
                        "birthday": params.birthday,
                        "expectedDay": params.expectedDay,
                        "pregnancyDay": params.pregnancyDay
                    }
                    var age = $outPatientServers.getFollowupAge(paramsAge, target)
                    return age.age
                },
                /**
                 * 照片预览
                 */
                handlePictureCardPreview: function (file) {
                    this.photoShare.preview.imgSrc = file.url
                    this.photoShare.preview.show = true
                },
                /**
                 * 删除预览图片
                 */
                handleRemove: function (file, fileList) {
                    // console.log(file, fileList)
                },
                /**
                 * 发送图片
                 */
                handleSendPhoto: function () {
                    var that = this
                    this.photoShare.listLength = this.$refs.photo.uploadFiles.length
                    if (this.photoShare.listLength === 0) return this.$message.error('未选择图片')
                    this.photoShare.loading = true
                    this.$refs.photo.uploadFiles.forEach(function (item) {
                        that.uploadServer(item.raw)
                    })
                },
                uploadServer(file) {
                    let that = this
                    let formData = new FormData()
                    formData.append('file', file)
                    $bb.ajax({
                        url: URL + 'followup/img/save',
                        data: formData,
                        processData: false,  // 告诉jQuery不要去处理发送的数据
                        contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
                        success: function (res) {
                            if (res.success) {
                                that.photoShare.loading = false
                                that.photoShare.readyList = []
                                that.$refs.photo.abort()
                                that.$refs.photo.uploadFiles = []
                                // that.$message.success('上传成功')

                                that.sendOwnServer(res.data)
                            } else {
                                that.$message.error('上传失败')
                            }
                        }
                    })

                },
                /**
                 * 获取到签名等信息然后发送 oss
                 * @param {*} data
                 */
                sendOss: function (data, file) {
                    var that = this
                    var formData = new FormData()
                    var name = data.dir + file.name.split('.')[0] + new Date().getTime()
                    formData.append('key', name)
                    formData.append('policy', data.policy)
                    formData.append('OSSAccessKeyId', data.accessId)
                    formData.append('success_action_status', 200),
                        formData.append('Signature', data.signature)
                    formData.append('file', file)
                    var xhr = new XMLHttpRequest()
                    xhr.open('post', data.host, true)
                    xhr.onreadystatechange = function () {
                        if (this.readyState == 4) {
                            that.photoShare.listLength--
                            that.photoShare.readyList.push(data.host + name)
                            if (that.photoShare.listLength == 0) {
                                that.sendOwnServer()
                            }
                        }
                    }
                    xhr.send(formData)
                },
                /**
                 * 将地址发送到自己的服务器上
                 */
                sendOwnServer: function (data) {
                    // var name = data.dir + file.name.split('.')[0] + new Date().getTime()
                    this.photoShare.readyList.push(data.imgUrl)
                    var that = this
                    var param = {
                        userId: this.photoShare.userId,
                        photoUrls: this.photoShare.readyList
                    }

                    $bb.ajax({
                        url: URL + 'followup/ptUserSharePhoto/add',
                        data: JSON.stringify(param),
                        success: function (res) {
                            if (res.success) {
                                that.photoShare.loading = false
                                that.photoShare.readyList = []
                                that.$refs.photo.abort()
                                that.$refs.photo.uploadFiles = []
                                that.$message.success('上传成功')
                                // that.getPhotoList('refresh')
                            } else {
                                that.$message.error('上传失败')
                            }
                        }
                    })
                },
                /**
                 * 获取 oss 签名
                 * @param {*} file
                 */
                getOssPolicy: function (file) {

                    var that = this
                    $bb.ajax({
                        url: URL + 'followup/aliyun/oss/getPolicy',
                        data: JSON.stringify({
                            data: file
                        }),
                        success: function (data) {
                            if (!data.success) return that.$message.error('获取oss签名失败')
                            that.sendOss(data.data, file)
                        }
                    })
                },
                /**
                 * 加载更多
                 */
                handleMore: function () {
                    if (this.photoShare.history.text === '没有更多了') return
                    this.photoShare.history.current++
                    // this.getPhotoList()
                },
                /**
                 * 获取照片历史
                 */
                getPhotoList: function (type) {
                    var that = this
                    var param = {
                        currentPage: this.photoShare.history.current,
                        pageSize: this.photoShare.history.size,
                        userId: this.photoShare.userId,
                        tenantId: this.photoShare.tenantId
                    }
                    this.photoShare.history.loading = true
                    // $bb.ajax({
                    // 	url: URL + 'followup/ptUserSharePhoto/historyPage',
                    // 	data: JSON.stringify(param),
                    // 	success: function (res) {
                    // 		if (res.success) {
                    // 			if (res.data.data.length != 0) {
                    // 				if (type === 'refresh') {
                    // 					that.photoShare.history.list = res.data.data
                    // 				} else {
                    // 					res.data.data.forEach(function (item) {
                    // 						that.photoShare.history.list.push(item)
                    // 					})
                    // 				}
                    // 				that.photoShare.history.list.forEach(function (item) {
                    // 					item.photoUrls.reverse()
                    // 				})
                    // 				that.photoShare.history.show = true
                    // 			} else {
                    // 				that.photoShare.history.text = '没有更多了'
                    // 				that.photoShare.history.current = that.photoShare.history.current = 1 ? 1 : that.photoShare.history.current--
                    // 			}
                    // 		} else {
                    // 			that.$message.error('获取照片失败')
                    // 		}
                    // 		that.photoShare.history.loading = false
                    // 	}
                    // })
                }


            }
        })
    }

    /**
     * 请求任务列表成功后的回调方法
     */
    var getTasksCallback = function (rows, params) {
        _taskGroup = rows
        $outPatientUi.taskBabycardInit({	// 个人信息
            id: "taskBabycard",
            list: params,
        })

        var curInfo = $outPatientServers.getCurInfo(rows, params.taskId)
        refreshTasksUi(rows, curInfo)
        var addTaskInfo = $outPatientServers.getAddTaskInfo(rows)	// 添加临时随访
        var index = $outPatientServers.getTaskIndexByTaskId(rows, curInfo.taskId)
        onNavbarRollInit(index)
        $(".show-wrapper > div.row").unbind("click")
        $(".show-wrapper > div.row").data({rows: rows, curInfo: curInfo, params: params, addTaskInfo: addTaskInfo})
        $(".show-wrapper > div.row").click(onTaskSelect)
        $(".show-wrapper > div.row").eq(index).click()
        // 点击taskBabycard跳转到建档（此页面的建档）
        $("#taskBabycard").unbind("click")
        $("#taskBabycard").data({flag: true, rows: rows, curInfo: curInfo, params: params, addTaskInfo: addTaskInfo})
        $("#taskBabycard").click(onTaskSelect)
    }
    /**
     * 删除任务列表成功后的回调方法
     */
    var deleteTasksCallback = function (rows, params) {
        $outPatientUi.taskBabycardInit({	// 个人信息
            id: "taskBabycard",
            list: params,
        })
        params.taskId = rows[rows.length - 1].taskId
        var curInfo = $outPatientServers.getCurInfo(rows, params.taskId)
        refreshTasksUi(rows, curInfo)
        var addTaskInfo = $outPatientServers.getAddTaskInfo(rows)	// 添加临时随访
        var index = $outPatientServers.getTaskIndexByTaskId(rows, curInfo.taskId)
        onNavbarRollInit(index)
        $(".show-wrapper > div.row").unbind("click")
        $(".show-wrapper > div.row").data({rows: rows, curInfo: curInfo, params: params, addTaskInfo: addTaskInfo})
        $(".show-wrapper > div.row").click(onTaskSelect)
        $(".show-wrapper > div.row").eq(index).click()
        // 点击taskBabycard跳转到建档（此页面的建档）
        $("#taskBabycard").unbind("click")
        $("#taskBabycard").data({flag: true, rows: rows, curInfo: curInfo, params: params, addTaskInfo: addTaskInfo})
        $("#taskBabycard").click(onTaskSelect)
    }
    event.getTasksCallback = function (rows, params) {
        getTasksCallback(rows, params)
    }
    /**
     * 删除患者
     */
    var onPatientDelect = function () {
        var params = $(this).data("params")
        $bb.toastConfirmShow($outPatientServers.ajaxDelPatient, params, "确定从该队列中删除患者?")
    }
    event.onPatientDelect = function () {
        onPatientDelect()
    }
    /**
     * 重置患者问卷数据
     */
    var onResetData = function () {
        var params = $(this).data("params")
        $bb.toastConfirmShow(function () {
            params.curInfo.status = "default"
            $.each(Object.keys(params.data.values), function (index, b) {
                if (params.data.values[b].indexOf("[") != -1 && b.indexOf("sf") != 0) {
                    params.data.values[b] = "[]"
                } else {
                    delete params.data.values[b]
                }
            })
            params.data.questiones.map(function (a, index1) {
                a.map(function (b) {
                    b.children.map(function (c) {
                        if (index1 == 0 && c.id != "gfy_xsekgwejd_yc" && c.id != "gfy_xsekgwejd_cc") {
                            c.val = ""
                        }
                        if (c.list instanceof Array) {
                            c.list.map(function (d, index) {
                                var ids = "gfyxsek_sf_nkfzl,sfzhidaoAyd01"
                                d.flag = index == 0 && ids.indexOf(c.id) == -1 ? true : false
                                var onChecked = "16TS0I20ABeRmzqzOQ5w,160j7QDK3PHoHaXxYBeU,16xRRfs8r2dtBrcQI2ce,164fXgfwyBWUyrSM1GX5,16wIVFIjTWxJsMHe2oK7,16KErFgFn8FzF5Xto6ld,16bhBmWbQMoMuTZLAizC,16vmgmL1jdBpKRfX3eME,16V31a5NUr64VaKXNfeM,16Q2W6KlrGNUZ8me5D99,167hUV1XU7r7Jf85p2b3"
                                var towChecked = "16Q2W6KlrGNUZ8me5D99"
                                var ids2 = "gfy_xsekgwejd_yjzym,sf3_ymjzzd,sf4_ymjzzd,sf6_ymjzzd,sf18_ymjzzd,sf21_ymjzzd,sf8_ymjzzd,gfy_xsekgwejd_yjzym"
                                if (ids2.indexOf(c.id) != -1 && (index == 0 || (onChecked.indexOf(params.data.task.ptTaskId) != -1 && index == 1) || (towChecked.indexOf(params.data.task.ptTaskId) != -1 && index == 2))) {
                                    d.flag = true
                                }
                                if (c.relationId) {
                                    d.flag = false
                                    c.valText = ""
                                }
                            })

                        }
                        if (c.children instanceof Array) {
                            c.children.map(function (e) {
                                if (e.list instanceof Array) {
                                    e.list.map(function (f, index) {
                                        f.flag = index == 0 && index1 == 1 ? true : false
                                    })
                                }
                                e.val = ""
                            })
                        }


                        if (index1 == 1) {
                            var ids = "sf"
                            if ((c.id + "").indexOf(ids) == -1 || c.id == "sf24_tj" || c.id.indexOf("qtzdjy") != -1 || c.id.indexOf("ksswzhnl") != -1) {
                                c.val = ""
                            }

                        }
                    })
                })
            })
            console.info(params.data)
            getQuestionCallback(params.data, params.params, params.curInfo, params.addTaskInfo)
        }, params, "确定清除本条填写数据?")
    }
    event.onResetData = function () {
        onResetData()
    }
    /**
     * 重置患者问卷数据
     */
    var onDeleteTemporary = function () {
        var params = $(this).data("params")
        $bb.toastConfirmShow($outPatientServers.ajaxDeleteTemporary, params, "确定删除当前临时随访问卷?")
    }
    event.onDeleteTemporary = function () {
        onDeleteTemporary()
    }


    /**
     * 2021 11 26
     * 根据 两个值计算第三个值 广三特有
     */
    $('.content-main').on('blur', 'input[name=zcey_tz-g]', function () {
        _computed_val(type1, 2)
        _computed_val(type2, 1)
    })

    // 1、特殊医疗配方
    var type1 = {
        param1: '',
        param2: '',
        timer: '',
        showDomName: 'zcey_tsylpfA'
    }
    $('.content-main').on('change', 'select[name=zcey_tsylpf]', function (event) {
        type1.param1 = getValId($(this).val())
        _computed_val(type1, 1)
    })
    $('.content-main').on('blur', 'input[name=zcey_tsylpfjl]', function (event) {
        type1.param2 = $(this).val()
        _computed_val(type1, 1)
    })

    // 2、铁剂名称
    var type2 = {
        param1: '',
        param2: '',
        timer: undefined,
        showDomName: 'zcey_tiejiA'
    }
    $('.content-main').on('change', 'select[name=zcey_tiejimc]', function (event) {
        type2.param1 = getValId($(this).val())
        if (!type2.param1) return
        _computed_val(type2, 2)

    })
    $('.content-main').on('blur', 'input[name=zcey_tieji]', function () {
        type2.param2 = $(this).val()
        _computed_val(type2, 2)
    })

    function getValId(val) {
        var v = val.split('')[0]
        if (Number(v) !== Number(v)) return null
        return Number(v)
    }

    function _computed_val(data, type) {
        var _param1 = data.param1
        var _param2 = data.param2
        var _weight = $('input[name=zcey_tz-g]').val() / 1000
        if (!_weight || !_param1 || !_param2) return
        type == 1 && _renderTeShu(_param1, _param2, _weight)
        type == 2 && _renderTieji(_param1, _param2, _weight)
    }

    function _renderTieji(_param1, _param2, _weight) {
        $bb.get(
            URL + 'followup/gy3y/webapi/query_tieji?id=' + _param1 + '&value=' + _param2 + '&weight=' + _weight,
            {},
            function (res) {
                $('input[name=zcey_tiejiA]').val(res.msg ? res.msg : res)
            }
        )
    }

    function _renderTeShu(_param1, _param2, _weight) {
        $bb.get(
            URL + '/followup/gy3y/webapi/query_teshu?id=' + _param1 + '&value=' + _param2 + '&weight=' + _weight,
            {},
            function (res) {
                $('input[name=zcey_tsylpfdbzA]').val(res[1])
                $('input[name=zcey_tsylpfzfA]').val(res[2])
                $('input[name=zcey_tsylpfvdA]').val(res[3])
                $('input[name=zcey_tsylpfgA]').val(res[4])
            }
        )
    }


    /**
     * 自动计算住院天数
     */
    $('.content-main').on('blur', 'input[name=zcejd_ruyrq]', function () {
        computeDays()
    })
    $('.content-main').on('blur', 'input[name=Pub13x00010]', function () {
        computeDays()
    })

    function computeDays() {
        var enterDate = $('input[name=zcejd_ruyrq]').val()
        var outDate = $('input[name=Pub13x00010]').val()
        if (!enterDate || !outDate) return
        enterDate = new Date(enterDate).getTime()
        outDate = new Date(outDate).getTime()
        var reduce = Math.floor(outDate / 1000) - Math.floor(enterDate / 1000)
        var oneDay = 3600 * 24
        var day = Math.ceil(reduce / oneDay)
        $('input[name=zcejd_zyts]').val(day)
    }

    /**
     * 自动计算体重增长
     */
    $('.content-main').on('blur', 'input[name=zcejd_cstz]', function () {
        computeWeight()
        getPValue('00001', $('input[name=zcejd_cstz]').val(), 0, 'zcejd_tzpz')
    })
    $('.content-main').on('blur', 'input[name=zcejd_cytz]', function () {
        computeWeight()
        getPValue('00001', $('input[name=zcejd_cytz]').val(), getDiffDays(), 'zcejd_cytzpz')
    })

    function computeWeight() {
        var before = $('input[name=zcejd_cstz]').val()
        var after = $('input[name=zcejd_cytz]').val()
        var val = after - before
        $('input[name=zcejd_cytzzz]').val(val)
    }

    /**
     * 获取出生身长
     */
    $('.content-main').on('blur', 'input[name=zcejd_cssc]', function () {
        getPValue('00002', $('input[name=zcejd_cssc]').val(), 0, 'zcejd_scpz')
    })

    /**
     * 获取出生头围
     */
    $('.content-main').on('blur', 'input[name=zcejd_cstw]', function () {
        getPValue('00003', $('input[name=zcejd_cstw]').val(), 0, 'zcejd_twpz')
    })

    /**
     * 获取出院身长
     */
    $('.content-main').on('blur', 'input[name=zcejd_cysc]', function () {
        getPValue('00002', $('input[name=zcejd_cysc]').val(), getDiffDays(), 'zcejd_cyscpz')
    })

    /**
     * 获取出院头围
     */
    $('.content-main').on('blur', 'input[name=zcejd_cytw]', function () {
        getPValue('00003', $('input[name=zcejd_cytw]').val(), getDiffDays(), 'zcejd_cytwpz')
    })

    /**
     * 获取出生时的 p 值
     * @param { string } type
     * @param { string } val
     */
    function getPValue(type, val, age, target) {
        var gender = $('input[name=Pub1100003]:checked').val()
        var pweek = $($('select[name=Pub1100006]')[0]).val()
        var pday = $($('select[name=Pub1100006]')[1]).val()

        if (!type || !val || !gender) return
        if (age != 0 && !age) return
        gender = gender == '男' ? "N" : "F"
        $bb.ajax({
            url: URL + 'followup/service/patient/growth/getPercentiles',
            data: JSON.stringify({
                data:
                    {
                        type: type,
                        gender: gender,
                        age: age,
                        value: val,
                        pweek: pweek,
                        pday: pday
                    }
            }),
            success: function (res) {
                // if (res.data.percentiles == '<3%') {
                // 	$(`select[name=${target}]`).val('<P3')
                // } else if (res.data.percentiles == '>97%') {
                // 	$(`select[name=${target}]`).val('>P97')
                // } else {
                // 	$(`select[name=${target}]`).val('P3～P97')
                // }
                $(`select[name=${target}]`).val(res.data.percentiles)
            }
        })
    }

    function getDiffDays() {
        var birth = $('input[name=Pub1100004]').val()
        var target = $('input[name=Pub13x00010]').val()
        if (!birth || !target) return 0
        birth = Math.floor(new Date(birth).getTime() / 1000)
        target = Math.floor(new Date(target).getTime() / 1000)
        var day = 3600 * 24
        var reduce = Math.ceil((target - birth) / day)
        console.log(reduce)
        return reduce
    }

    function checkAllNo(ele) {
        let name = $(ele).attr('name')
        console.log('name', name)
        console.log('el', $(ele).attr('checked'))
        if ($(ele).attr('checked') == 'checked') {
            $(ele).parent().parent().parent().nextAll().each(function (i, value) {
                if ($(value).children().children().children().attr('value') == '无') {
                    $(value).children().children().children().eq(0).attr('checked', 'true')
                }
            })
        } else {
            // $('input[type=radio]').each(function (i, value) {
            // 	if ($(value).attr('name').indexOf(name) > -1) {
            // 		$(value).removeAttr('checked')
            // 	}
            // })
            $(ele).parent().parent().parent().nextAll().each(function (i, value) {
                if ($(value).children().children().children().attr('value') == '无') {
                    $(value).children().children().children().removeAttr('checked')
                }
            })
        }
    }

    //3月龄预警征象选择全无
    $('.content-main').on('click', 'input[type=radio][name="sf_yjz_March_qw"]', function () {
        checkAllNo(this)
    })

    //6月龄预警征象选择全无
    $('.content-main').on('click', 'input[type=radio][name="sf_yjz_June_qw"]', function () {
        checkAllNo(this)
    })
    //8月龄预警征象选择全无
    $('.content-main').on('click', 'input[type=radio][name="sf_yjz_August_qw"]', function () {
        checkAllNo(this)
    })
    //12月龄预警征象选择全无
    $('.content-main').on('click', 'input[type=radio][name="sf_yjz_Dec_qw"]', function () {
        checkAllNo(this)
    })
    //18月龄预警征象选择全无
    $('.content-main').on('click', 'input[type=radio][name="sf_yjz_sby_qw"]', function () {
        checkAllNo(this)
    })
    //2岁预警征象选择全无
    $('.content-main').on('click', 'input[type=radio][name="sf_yjz_essy_qw"]', function () {
        checkAllNo(this)
    })
    //2岁半预警征象选择全无
    $('.content-main').on('click', 'input[type=radio][name="sf_yjz_Lsb_qw"]', function () {
        checkAllNo(this)
    })
    //3岁预警征象选择全无
    $('.content-main').on('click', 'input[type=radio][name="sf_yjz_ssui_qw"]', function () {
        checkAllNo(this)
    })


    $('.content-main').on('click', '.anchor-menu-list li.active a', function () {
        let id = $(this).prop('id')
        let collapse = $('#' + id).attr("collapse")
        if (collapse == "true") {
            $('#' + id).attr("collapse", "false")
            $('#' + id).find("i.fa-plus-square-o").addClass("fa-minus-square-o").removeClass("fa-plus-square-o")
            $('#' + id).next().show()
        } else {
            $('#' + id).attr("collapse", "true")
            $('#' + id).find("i.fa-minus-square-o").addClass("fa-plus-square-o").removeClass("fa-minus-square-o")
            $('#' + id).next().hide()
        }
    })


    return event
})
